package com.tsinghuabigdata.edu.ddmath.module.ddwork.bean;

import android.os.SystemClock;
import android.text.TextUtils;

import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.constant.ErrTag;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.WorkCommitListener;
import com.tsinghuabigdata.edu.ddmath.requestHandler.MyLearnService;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AppLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * 保存在本地的作业页信息
 */
public class LocalPageInfo extends WorkPageInfo implements Serializable {

    private static final long serialVersionUID = 4705837390463621118L;


    public static final int ST_NONE  = 0;
    public static final int ST_UING  = 1;
    public static final int ST_ERROR = 2;
    public static final int ST_SUCC  = 3;

    //上传的状态
    private int uploadStatus = ST_NONE;       //， 0：没有上传， 1：上传中 2:上传错误 3：上传成功

    //作业图片
    private String localpath;       //图片保存在本地的路径

    //上传后的url
    private String url="";

    private String fileId;

    //作业ID
    private String workId;

    private boolean selected;

    private ArrayList<WorkCommitListener> mListeners;

//    private ArrayList<LocalQuestionInfo> questionInfos = new ArrayList<>();

    public LocalPageInfo( String workId ){
        this.workId = workId;
        fileId = System.currentTimeMillis()+"";
    }

    //for Localsave use
    public JSONObject getJsonObject(){
        JSONObject json = new JSONObject();
        try {

            if( uploadStatus == ST_SUCC ){
                json.put( "uploadStatus", ST_SUCC );
            }else{
                json.put( "uploadStatus", ST_NONE );
            }

            json.put( "localpath", localpath );
            json.put( "fileId", fileId );
            json.put( "workId", workId );
            json.put( "path", url );
            json.put( "page", pageNum );

            JSONArray jsonArray = new JSONArray();
            for( LocalQuestionInfo questionInfo : questions ){
                jsonArray.put( questionInfo.getJsonObject() );
            }
            json.put( "questions", jsonArray );

        }catch (Exception e){
            AppLog.i( e.toString() );
        }
        return json;
    }

    //for 上传使用
    public JSONObject getJson(){
        JSONObject json = new JSONObject();
        try {
            json.put( "path", url );
            json.put( "page", pageNum );

            JSONArray jsonArray = new JSONArray();
            for( LocalQuestionInfo questionInfo : questions ){
                jsonArray.put( questionInfo.getJson() );
            }
            json.put( "cutInfos", jsonArray );

        }catch (Exception e){
            AppLog.i( e.toString() );
        }
        return json;
    }

    public void setPageListener( ArrayList<WorkCommitListener> listeners ){
        mListeners = listeners;
    }

    public void copy( WorkPageInfo pageInfo ){
        pageNum = pageInfo.getPageNum();
        submitStatus = pageInfo.getSubmitStatus();

        if( questions == null ){
            questions = new ArrayList<>();

            for( QuestionInfo questionInfo : pageInfo.questions ){
                LocalQuestionInfo localQuestionInfo = new LocalQuestionInfo();
                localQuestionInfo.copy( questionInfo );
                questions.add( localQuestionInfo );
            }
        }else {
            int min_count = questions.size()<pageInfo.questions.size() ? questions.size() : pageInfo.questions.size();
            for( int i=0; i<min_count; i++ ){
                questions.get(i).copy( pageInfo.questions.get(i) );
            }
        }
    }
    //-----------------------------------------------------------------------------------------
//    public ArrayList<LocalQuestionInfo> getQuestionInfos() {
//        return questionInfos;
//    }
//
//    public void setQuestionInfos(ArrayList<LocalQuestionInfo> questionInfos) {
//        this.questionInfos = questionInfos;
//    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getLocalpath() {
        return localpath;
    }

    public void setLocalpath(String localpath) {
        this.localpath = localpath;
    }

//    public int getIndex() {
//        return index;
//    }
//
//    public void setIndex(int index) {
//        this.index = index;
//    }

    public int getUploadStatus() {
        return uploadStatus;
    }

    public void setUploadStatus(int uploadStatus) {
        this.uploadStatus = uploadStatus;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }

    //--------------------------------------------------------------------------------------
    public void startUpload(){
        for( LocalPageInfo uploadImage : uploadlist ){
            if( uploadImage.equals( this ) ){
                return;
            }
        }
        callbackListener( uploadStatus );
        uploadlist.add( this );
        startUploadThread();
    }

    private void callbackListener( int status ){
        if( mListeners!=null ){
            for( WorkCommitListener listener : mListeners ){
                listener.pageStatus( workId, status );
            }
        }
    }
    private void upload(){

        if( uploadStatus == ST_UING || uploadStatus == ST_SUCC )
            return;

        uploadStatus = ST_UING;
        callbackListener( uploadStatus );

        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if( loginInfo == null ){
            uploadStatus = ST_ERROR;
            callbackListener( uploadStatus );
            return;
        }

        MyLearnService learnService = ZxApplication.getLearnService();
        if( learnService == null ){
            uploadStatus = ST_ERROR;
            callbackListener( uploadStatus );
            return;
        }

        FileInputStream fis = null;
        try{
            File file = new File(localpath );
            fis = new FileInputStream( file );
        }catch (Exception e){
            AppLog.i( ErrTag.TAG_FILE, e.toString() );
        }
        if( fis == null ){
            uploadStatus = ST_ERROR;
            callbackListener( uploadStatus );
            return;
        }

        for( int i=0; i<3; i++ ){
            try{
                String path = learnService.uploadImage( fileId, loginInfo.getAccessToken(), fis );
                if( !TextUtils.isEmpty(path) ){
                    url = path;
                    uploadStatus = ST_SUCC;
                    callbackListener( uploadStatus );
                    fis.close();
                    return;
                }
                SystemClock.sleep(50);
            }catch (Exception e){
                AppLog.i(ErrTag.TAG_HTTP, e.toString() );
            }
        }
        //
        try {
            fis.close();
        }catch (Exception e){
            AppLog.d(e.toString());
        }
        uploadStatus = ST_ERROR;
        callbackListener( uploadStatus );
    }

    //------------------------------------------------------------------
    //由于不能同时上传，现在改为依次上传
    private static ArrayList<LocalPageInfo> uploadlist = new ArrayList<>();

    private static final int THREAD_IDLE = 0;
    private static final int THREAD_RUN = 1;

    private static int run_status = THREAD_IDLE;

    public static void stopUploadThread(){
        run_status = THREAD_IDLE;
    }
    private static void startUploadThread(){
        if( run_status == THREAD_RUN )
            return;
        run_status = THREAD_RUN;

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    if( uploadlist.size() == 0 || run_status == THREAD_IDLE)
                        break;

                    AppLog.d("pppppp uploadlist size = " + uploadlist.size() );
                    long time = System.currentTimeMillis();
                    LocalPageInfo pageInfo = uploadlist.get(0);
                    pageInfo.upload();
                    uploadlist.remove( pageInfo );
                    AppLog.d("pppppp upload time = " + ( System.currentTimeMillis() - time ) );
                }
                run_status = THREAD_IDLE;
            }
        }).start();
    }

}
